//
//  ChoiceViewController.m
//  NewNest
//
//  Created by 王阳阳 on 16/3/9.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ChoiceViewController.h"
#import "NewNestHeader.h"
#import "BCCalendarViewController.h"



@interface ChoiceViewController ()<UITableViewDelegate,UITableViewDataSource>

// 布局
@property (nonatomic, strong) UITableView *chooseTableVIew;
// 数据解析
@property (nonatomic, strong) NSMutableArray *chooseArray;
/**< 用来保存上拉加载时变化的数字 */
@property (nonatomic, assign) NSInteger number;


@end

@implementation ChoiceViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        NSLog(@"SK == %s", __FUNCTION__);
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // navi
//    self.tabBarController.tabBar.tintColor = [UIColor cyanColor];
    self.navigationController.navigationBar.translucent = NO;
    
    self.upView = [[ChooseTableView alloc]initWithFrame:CGRectMake(20, 0, SVIEW_FW, SVIEW_FH - 517)];
//    [self.view addSubview:self.upView];
    self.navigationItem.title = @"精选";
//    self.tabBarController.tabBar.tintColor = [UIColor cyanColor];
    
    [self createHandleDate];
    
    // 初始化视图
    [self createTableView];
    
    // 导航栏和tabBar的隐藏
//    [self hidden];
    
    //给保存上拉加载的数字设置初始值
    self.number = 2;
    // 下拉刷新
//    [self refresh];
    
   


}



#pragma mark - HandleDate
-(void)createHandleDate
{
    
//    // 获取数据
    NSString *urlStr = @"http://ihome.cmfmobile.com:8080/sp/custom/getIndexProjectList.do?pn=1";
    
    [AFNetworking GETWithURL:urlStr completion:^(id result) {
        self.chooseArray = [ChoiceModel modelHanderWithArray:result];
        [_chooseTableVIew reloadData];
    }];
}

#pragma mark - 创建TableView
-(void)createTableView
{
    // tableView的创建
    self.chooseTableVIew = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _chooseTableVIew.delegate = self;
    _chooseTableVIew.dataSource = self;
    
    UIView *weather = [[UIView alloc]initWithFrame:CGRectMake(20, 0, SVIEW_FW, SVIEW_FH - 517)];
    UILabel *sss = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, weather.width, 30)];
    sss.text = @"☀️ ☁️ ☔️ ❄️";
    sss.textAlignment = NSTextAlignmentLeft;
    sss.textColor = [UIColor  colorWithRed:219/255. green:219/255. blue:219/255. alpha:1];
    [weather addSubview:sss];
    
//    weather.backgroundColor = [UIColor grayColor];
    UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"homeone.png"]];
    image.alpha = .8;
    image.frame = CGRectMake(20, 30, weather.frame.size.width - 40, weather.frame.size.height - 20);
    
    image.layer.borderColor = [UIColor colorWithRed:219/255. green:219/255. blue:219/255. alpha:.5].CGColor;
    image.layer.borderWidth = 10;
    image.layer.cornerRadius = 5;
    image.clipsToBounds = YES;
    image.userInteractionEnabled = YES;
    
    [weather addSubview:image];
    
    
        self.chooseTableVIew.tableHeaderView = weather;

    
    _chooseTableVIew.backgroundColor = [UIColor clearColor];
    [_chooseTableVIew registerClass:[ChoiceTableviewCell class] forCellReuseIdentifier:@"cell"];
    
    UIButton *wea = [UIButton buttonWithType:UIButtonTypeCustom];
    wea.frame = CGRectMake(0, 0, SVIEW_FW, 30);
    [wea addTarget:self action:@selector(weather) forControlEvents:UIControlEventTouchUpInside];
    [self.chooseTableVIew.tableHeaderView addSubview:wea];
    
    [self.view addSubview:_chooseTableVIew];
    
    
   
    
    //右上角的搜索按钮
    UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@""] style:UIBarButtonItemStylePlain target:self action:@selector(search)];
        [searchButton setTitle:@"搜索"];
    self.navigationItem.rightBarButtonItem = searchButton;
    
    
    
    //左上角扫一扫按钮
    UIBarButtonItem *scanButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@""] style:UIBarButtonItemStylePlain target:self action:@selector(scan)];
        [scanButton setTitle:@"日程"];
    self.navigationItem.leftBarButtonItem = scanButton;
}

// 设置cell个数
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _chooseArray.count;
}

/// 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChoiceTableviewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    
    
    //取消点击cell变灰
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
//     判断当前是什么模式
    BOOL model = [AccountManager sharedInstance].isNight;
    if (model == YES) {
        cell.backgroundColor = [UIColor changeColorWithString:@"#a1a3a6"];
    } else {
        cell.backgroundColor = [UIColor clearColor];
    }
    
    //数组保护
    if (_chooseArray.count != 0) {
        ChoiceModel *m = _chooseArray[indexPath. row];
        NSMutableArray *arr = m.imageUrl;
        [cell.img sd_setImageWithURL:[NSURL URLWithString:arr[0]] placeholderImage:[UIImage imageNamed:@"heng"]];
        cell.titleLabel.text = m.name;
        cell.styleLabel.text = m.style;
        cell.squareLabel.text = m.space;
        cell.priceLabel.text = m.price;
        return cell;
    }else{
        return cell;
    }
}

/// 设置cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [UIScreen mainScreen].bounds.size.height / 3;
}

/// 点击cell进入详情页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChooseDetailViewController *boutiqueDetailVC = [[ChooseDetailViewController alloc] init];
    ChoiceModel *m = _chooseArray[indexPath.row];
    boutiqueDetailVC.modal = m;
    [self.navigationController pushViewController:boutiqueDetailVC animated:YES];
    
}

/// 导航栏隐藏
//- (void)hidden
//{
//    // 导航栏隐藏设置
//    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
//        // 取消ScrollView的内容自动调整
//        self.automaticallyAdjustsScrollViewInsets = NO;
//        //tableView边界预留
//        UIEdgeInsets insets = self.chooseTableVIew.contentInset;
//        // 让上边界的预留值和导航栏相等
//        insets.top = self.navigationController.navigationBar.bounds.size.height;
//        //把修改后的边界预留值赋给tableView
//        self.chooseTableVIew.contentInset = insets;
//        // 滚动指标点到滚到视图的边缘的距离
//        self.chooseTableVIew.scrollIndicatorInsets = insets;
//    }
//}

// 导航栏滚动
//- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
//{
//    if (velocity.y > 0) {
//        self.navigationController.navigationBar.hidden = YES;
//        self.tabBarController.tabBar.hidden = YES;
//    }else{
//        self.navigationController.navigationBar.hidden = NO;
//        self.tabBarController.tabBar.hidden = NO;
//    }
//}

/// 当tableview停止减速 导航栏出现
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
//{
//    self.navigationController.navigationBar.hidden = NO;
//    self.tabBarController.tabBar.hidden = NO;
//    
//}

/// 下拉刷新, 上拉加载
//- (void)refresh
//{
//    // 下拉刷新
//    self.chooseTableVIew.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandler)];
//    // 开始刷新
//    [self.chooseTableVIew.mj_header beginRefreshing];
//    
//    
//    //上拉加载
//    self.chooseTableVIew.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
//    //如果数据字典不为空 那么就刷新请求新的数据
//    if (_chooseArray.count != 0) {
//        [self.chooseTableVIew.mj_footer beginRefreshing];
//    }
//    
//}

/// 上拉加载方法
- (void)loadNewData
{
//    NSString *urlStr = [NSString stringWithFormat:@"http://ihome.cmfmobile.com:8080/sp/custom/getIndexProjectList.do?pn=%ld", (long)self.number];
//    
//    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    [session GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"精选加载更多成功");
//        // 定义一个数组 用来保存新请求到的数据
//        NSMutableArray *newDataArr = [NSMutableArray array];
//        newDataArr = [NSMutableArray arrayWithArray:[BoutiqueModal modelHanderWithArray:responseObject]];
//        //
//        for (NSInteger i = 0; i < newDataArr.count; i++) {
//            BoutiqueModal *m = newDataArr[i];
//            if (m.name == nil) {
//                [newDataArr removeObject:m];
//            }
//        }
//        
//        //将新请求到的数据依次载入到保存数据的数组里面
//        for (NSInteger i = 0; i < newDataArr.count; i++) {
//            [self.dataArr addObject:newDataArr[i]];
//        }
//        //刷新tableView
//        [_tableview reloadData];
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"精选加载更多失败");
//    }];
//    
//    // 结束刷新
//    [self.tableview.mj_footer endRefreshing];
//    //将保存刷新的动态数据加一
//    self.number += 1;
}


-(void)weather
{
    NSLog(@"天气啊");
    
    WeatherTableViewController *weatherVC = [[WeatherTableViewController alloc]init];
    [self.navigationController pushViewController:weatherVC animated:YES];
}

/// 搜索栏的方法实现
- (void)search
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];//    [self presentViewController:searchNavi animated:YES completion:nil];
}


-(void)scan
{
    NSLog(@"日历动态");
     BCCalendarViewController *calendar = [[BCCalendarViewController alloc]init];
    [self.navigationController pushViewController:calendar animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
